package com.example.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.util.StringUtils;
//import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;

/**
 * TODO
 *
 * @author CSD
 * @date 2022-07-28 14:16
 */
public class AESUtils {

    private static final String CHARSET_NAME = "UTF-8";

    private static final String AES_NAME = "AES";
    // 加密模式
    public static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    // 密钥
    public static final String KEY = "1954682168745975";
    // 偏移量
    public static final String IV = "1954682168745975";


    /**
     * 加密
     *
     * @param content
     * @return
     */
    public static String encrypt(String content) {
        byte[] result = null;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(CHARSET_NAME), AES_NAME);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);
            result = cipher.doFinal(content.getBytes(CHARSET_NAME));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64.encodeBase64String(result);
    }

    /**
     * 解密
     *
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(CHARSET_NAME), AES_NAME);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
            return new String(cipher.doFinal(Base64.decodeBase64(content)), CHARSET_NAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    //测试一下
    public static void main(String[] args) throws Exception {
        String password = "123";
        String encrypt = encrypt(password);
        System.out.println(encrypt);
        String decrypt = decrypt("WdL1RvSkRdC/l4/pxGgpjg==");
        System.out.println(decrypt);
    }
}
